"""
这里写模型
"""

from exts import db
from datetime import datetime


class UserModel(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(100), nullable=False)                # 用户名
    password = db.Column(db.String(200), nullable=False)                # 密码
    email = db.Column(db.String(100), nullable=False, unique=True)      # QQ邮箱, unique=True:只能出现一个qq邮箱, 不能有相同的
    join_time = db.Column(db.DateTime, default=datetime.now)            # 用户注册时间


class EmailCaptchaModel(db.Model):
    __tablename__ = "email_captcha"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(100), nullable=False)       # 邮箱
    captcha = db.Column(db.String(100), nullable=False)     # 验证码
    # used = db.Column(db.Boolean, default=False)


class QuestionModel(db.Model):
    __tablename__ = "question"
    #
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    title = db.Column(db.String(100), nullable=False)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)

    author_id = db.Column(db.Integer, db.ForeignKey("user.id"))     # 外键, 关联user表的id

    # 反向引用, 关联user表的author字段
    author = db.relationship(UserModel, backref="questions")


class AnswerModel(db.Model):
    __tablename__ = "answer"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    content = db.Column(db.Text, nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)

    question_id = db.Column(db.Integer, db.ForeignKey("question.id"))   # 外键, 关联question表的id
    author_id = db.Column(db.Integer, db.ForeignKey("user.id"))         # 外键, 关联user表的id

    # 反向引用, 关联question表的question字段
    question = db.relationship(QuestionModel, backref=db.backref("answers", order_by=create_time.desc()))
    author = db.relationship(UserModel, backref="answers")              # 反向引用, 关联user表的author字段
